//TODO
#include <iostream>
#include <stdexcept>
#include <string>
#include <list>

using namespace std;
//TODO
class goods{
public:
    goods(string name, int amount) : name(name), amount(amount) {}
    string getName() const { return name; }
    int getAmount() const { return amount; }
private:
    string name;
    int amount;
};

class stock{
public:
    void purchase(const goods& g);
    void sell(const goods& g);
    void print();
private:
    list<goods> goodsList;
};
void stock::purchase(const goods& g){
    for (auto& i : goodsList){
        if (i.getName() == g.getName()){
            i=goods(i.getName(), i.getAmount()+ g.getAmount());
            return;
        }
    }
    goodsList.push_back(g);
}
void stock::sell(const goods& g){
    for (auto it=goodsList.begin(); it!=goodsList.end(); it++){
        if (it->getName() == g.getName()){
            if (it->getAmount() < g.getAmount()){
                string error_message="Error: insufficient inventory of "+it->getName();
                throw domain_error(error_message);
                return;
            }
            *it=goods(it->getName(), it->getAmount()- g.getAmount());
            if (it->getAmount() == 0){
                string warning_message="Warning: Inventory of "+it->getName()+" is 0";
                goodsList.erase(it);
                throw domain_error(warning_message);
            }
            return;
        }
    }
    throw domain_error("No such goods");
    return;
}
void stock::print(){
    
    goodsList.sort([](const goods& a, const goods& b){return a.getAmount() > b.getAmount();});
    for (auto& i : goodsList){
        cout << i.getName() << "\t" << i.getAmount() << endl;
    }
    cout << endl;
    return;
}
int main()
{
    stock s;
    s.purchase(goods("pen", 100));
    s.purchase(goods("mouse", 50));
    s.purchase(goods("notepad", 200));
    s.purchase(goods("pen", 50));
    s.print();

    try{
        s.sell(goods("mouse", 50));
    }catch (domain_error e) {
        cout << e.what() << endl;
    }
    try{
        s.sell(goods("pen", 210));
    }catch (domain_error e) {
        cout << e.what() << endl;
    }

    return 0;
}
